/*
 * @Author: kevin.huang 
 * @Date: 2018-07-21 19:48:42 
 * @Last Modified by: kevin.huang
 * @Last Modified time: 2019-04-26 17:28:53
 * Copyright (c): kevin.huang Released under MIT License
 */
(function (global, factory) {
    if (typeof define === 'function' && define.amd  && !window["_all_in_"]) {
        define(['$B', 'toolbar', 'plugin'], function (_$B) {
            return factory(global, _$B);
        });
    } else {
        if(!global["$B"]){
            global["$B"] = {};
        }
        factory(global, global["$B"]);
    }
}(typeof window !== "undefined" ? window : this, function (window, $B) {
    var defaultOpts = {
        title: '', //标题
        iconCls: null, //图标class，font-awesome字体图标
        toolbar: null, //工具栏对象参考工具栏组件配置说明
        width: 'auto',
        height: 'auto',
        shadow: true, //是否需要阴影
        radius: true, //是否圆角
        header: true, //是否显示头部
        zIndex: 999999,
        content: null, //静态内容或者url地址
        url:'',//请求地址
        dataType: 'html', //当为url请求时，html/json/iframe
        draggable: false, //是否可以拖动
        moveProxy: false, //是否代理移动方式
        draggableHandler: 'header', //拖动触发焦点
        closeable: false, //是否关闭
        closeType: 'hide', //关闭类型 hide(隐藏，可重新show)/ destroy 直接从dom中删除
        expandable: false, //可左右收缩
        maxminable: false, //可变化小大
        collapseable: false, //上下收缩
        onResized: null, //function (pr) { },//大小变化事件
        onLoaded: null, //function () { },//加载后
        onClose: null, //关闭前
        onClosed: null, //function () { },//关闭后
        onExpanded: null, // function (pr) { },//左右收缩后
        onCollapsed: null, // function (pr) { }//上下收缩后
        onCreated: null //function($content,$header){} panel创建完成事件
    };
    var config = $B["config"];
    var iframeHtml = "<iframe  class='panel_content_ifr' frameborder='0' style='overflow:visible;height:100%;width:100%;display:block;vertical-align:top;'  src='' ></iframe>";
    var loadingHtml = "<div class='k_box_size' style='position:absolute;z-index:2147483600;width:100%;height:26px;top:2px;left:0;' class='loading'><div class='k_box_size' style='filter: alpha(opacity=50);-moz-opacity: 0.5;-khtml-opacity: 0.5;opacity: 0.5;position:absolute;top:0;left:0;width:100%;height:100%;z-index:2147483600;background:#03369B;'></div><div class='k_box_size' style='width:100%;height:100%;line-height:26px;padding-left:16px;position:absolute;width:100%;height:100%;z-index:2147483611;color:#fff;text-align:center;'><i style='color:#fff;font-size:16px;' class='fa animate-spin fa-spin6'></i><span style='padding-left:5px;font-weight:bold;color:#fff;'>" + $B.config.loading + "</span></div></div>";
 
    var footToolbarHtml = '<div class="k_panel_foot_toolbar k_box_size" ></div>';
    var contentHtml = '<div class="k_panel_content k_box_size" >{c}</div>';
    var headerIconHtml = '<div style="padding-right:1px;height:100%;" class="k_panel_header_icon menu_img btn"><i style="font-size:16px;line-height:1.5em;" class="fa {icon}">\u200B</i></div>';
    var headerHtml = '<div class="k_panel_header"><div class="k_panel_header_content"><h1>{title}</h1><div class="k_panel_header_toolbar k_box_size"></div></div></div>';

    function Panel(jqObj, opts) {
        $B.extend(this, Panel); //继承父类
        var _this = this,
            c = "",
            headerHeight = 0,
            headerTop = 0;
        this.jqObj = jqObj.addClass("k_panel_main k_box_size");
        this.opts = $.extend({}, defaultOpts, opts);
        if (this.opts.shadow) {
            this.jqObj.addClass("k_box_shadow");
        }
        if (this.opts.radius) {
            this.jqObj.addClass("k_box_radius");
        }
        if (this.opts.header) {
            this.$header = $(headerHtml.replace("{title}", this.opts.title)).appendTo(this.jqObj);
            headerHeight = _this.$header.outerHeight();
            var _c = this.$header.children();
            headerTop = (headerHeight - 20) / 2;
            _c.children(".k_panel_header_toolbar").css("padding-top", headerTop);
        }
        var isUrl = false;
        var isString = typeof this.opts.content === "string";
        if (isString) {
            isUrl = $B.isUrl(this.opts.content);
        }
        if (!isUrl) {
            if (isString) {
                c = this.opts.content;
            }
        }
        this.$body = $(contentHtml.replace('{c}', c)).appendTo(this.jqObj).css({
            "border-top": "solid #ccc " + headerHeight + "px"
        });
        if(this.opts.bodyCss){
            this.$body.css(this.opts.bodyCss);
        }
        if (!isString && !isUrl) {
            this.$body.append(this.opts.content);
        }
        //加入工具栏功能
        this.toolArray = [];
        var toolbar;
        if (typeof this.opts.createToolsFn === 'function') { //由外部创建工具栏
            toolbar = $(footToolbarHtml).appendTo(this.jqObj);
            this.opts.createToolsFn.call(toolbar, this.opts.toolbar);
        } else {
            if (this.opts.toolbar) {
                toolbar = $(footToolbarHtml).appendTo(this.jqObj);
                var toolbarOpts ;
                if($.isArray( this.opts.toolbar)){
                    toolbarOpts = {buttons:this.opts.toolbar,"align":"center"};
                }else{
                    toolbarOpts = this.opts.toolbar;
                }
                this.toolArray.push(new $B.Toolbar(toolbar, toolbarOpts));
            }
        }
        var size = {
            height: this.opts.height,
            width: this.opts.width
        };
        this.jqObj.outerWidth(this.opts.width).outerHeight(this.opts.height).data("src_size", size);
        if (this.opts.iconCls != null && this.opts.header) {
            $(headerIconHtml.replace("{icon}", this.opts.iconCls)).prependTo(this.$header.children('.k_panel_header_content'));
        }
        if (this.opts.header) {
            var $toolbar = this.$header.children('.k_panel_header_content').children(".k_panel_header_toolbar");
            if (this.opts.closeable) {
                $("<a class='k_panel_tool_icon k_panel_close btn'><i class='fa fa-cancel'></i></a>").appendTo($toolbar).click(function () {
                    if (_this.opts.closeType === "hide") {
                        _this.close();
                    } else {
                        _this.destroy();
                    }
                    return false;
                });
            }
            if (this.opts.expandable) { //可左右收缩
                var isFunc = typeof _this.opts.onExpanded === 'function';
                var _extend = function (p) {
                    var $_t = p.children();
                    _this.jqObj.removeClass("k_panel_expandable_bg");
                    _this.jqObj.animate({
                        "width": _this.jqObj.data("lsWidth")
                    }, 10, function () {
                        p.siblings().show();
                        p.parent().prevAll().show();
                        _this.$header.css("border-bottom-width", "1px");
                        $_t.removeClass("fa-right-open-1").addClass("fa-left-open-2");
                        _this.jqObj.css("cursor", "default").off("click").children("div:gt(0)").fadeIn(100);
                        if (isFunc) {
                            setTimeout(function () {
                                _this.opts.onExpanded('right');
                            }, 1);
                        }
                    });
                };
                $("<a class='k_panel_tool_icon k_panel_slide_left btn'><i class='fa fa-left-open-2'></i></a>").appendTo($toolbar).click(function () {
                    var p = $(this);
                    var $_t = p.children();
                    if ($_t.hasClass("fa-left-open-2")) {
                        _this.jqObj.children("div:gt(0)").fadeOut(100, function () {
                            p.siblings().hide();
                            p.parent().prevAll().hide();
                            _this.$header.css("border-bottom-width", "0px");
                            _this.jqObj.data("lsWidth", _this.jqObj.width());
                            _this.jqObj.animate({
                                "width": 25
                            }, 10, function () {
                                _this.jqObj.addClass("k_panel_expandable_bg");
                                if (isFunc) {
                                    setTimeout(function () {
                                        _this.opts.onExpanded('left');
                                    }, 1);
                                }
                            }).css("cursor", "pointer").on("click", function () {
                                _extend(p);
                            });
                            $_t.removeClass("fa-left-open-2").addClass("fa-right-open-1");
                        });
                    } else {
                        _extend(p);
                    }
                    return false;
                });
            }
            if (this.opts.maxminable) { //可变化小大
                var $a = $("<a class='k_panel_tool_icon k_panel_maxbtn'><i class='fa fa-resize-full'></i></a>").appendTo($toolbar).click(function () {
                    var $_t = $(this).children(),
                        flag, pr;
                    if ($_t.hasClass("fa-resize-full")) {
                        var $parent = _this.jqObj.parent();
                        var zIndex = _this.jqObj.css("z-index");
                        _this.jqObj.data("zIndex", zIndex);
                        _this.jqObj.css("z-index", _this.opts.zIndex);
                        var p_width = $parent.width();
                        var p_height = $parent.height();
                        pr = {
                            width: p_width,
                            height: p_height
                        };
                        if (_this.opts.draggable) {
                            pr["top"] = 0;
                            pr["left"] = 0;
                            _this.jqObj.data("src_pos", _this.jqObj.position());
                        }
                        _this.jqObj.animate(pr, 100);
                        $_t.removeClass("fa-resize-full").addClass("fa-resize-small");
                        flag = "max";
                    } else {
                        var src_size = _this.jqObj.data("src_size");
                        pr = {
                            width: src_size.width,
                            height: src_size.height
                        };
                        if (_this.opts.draggable) {
                            var src_pos = _this.jqObj.data("src_pos");
                            pr["top"] = src_pos.top;
                            pr["left"] = src_pos.left;
                        }
                        _this.jqObj.css("z-index", _this.jqObj.data("zIndex"));
                        _this.jqObj.animate(pr, 100);
                        $_t.removeClass("fa-resize-small").addClass("fa-resize-full");
                        flag = "min";
                    }
                    if (typeof _this.opts.onResized === 'function') {
                        _this.opts.onResized(flag);
                    }
                    return false;
                });
                //加入双击功能
                if (this.$header) {
                    this.$header.data("_ck", $a);
                    this.$header.click(function () {
                        return false;
                    }).dblclick(function () {
                        $(this).data("_ck").trigger("click");
                        return false;
                    });
                }
            }
            if (this.opts.collapseable) { //上下收缩
                $("<a class='k_panel_tool_icon  btn'><i class='fa fa-down-open-2'></i></a>").appendTo($toolbar).click(function () {
                    var $_t = $(this).children();
                    var f;
                    if ($_t.hasClass("fa-down-open-2")) {
                        _this.jqObj.children("div:gt(0)").fadeOut(100, function () {
                            _this.jqObj.data("lsHeight", _this.jqObj.height());
                            _this.jqObj.animate({
                                "height": headerHeight
                            }, 200);
                            $_t.removeClass("fa-down-open-2").addClass("fa fa-up-open-2");
                        });
                        f = "down";
                    } else {
                        _this.jqObj.animate({
                            "height": _this.jqObj.data("lsHeight")
                        }, 100, function () {
                            _this.jqObj.children("div:gt(0)").fadeIn(100);
                            $_t.removeClass("fa-up-open-2").addClass("fa-down-open-2");
                        });
                        f = "up";
                    }
                    if (typeof _this.opts.onCollapsed === "function") {
                        setTimeout(function () {
                            _this.opts.onCollapsed(f);
                        }, 1);
                    }
                    return false;
                });
            }
        }
        if (this.opts.draggable) {
            var dragOpt = {
                isProxy: this.opts.moveProxy,
                onDragReady: this.opts.onDragReady, //鼠标按下时候准备拖动前，返回true则往下执行，返回false则停止
                onStartDrag: this.opts.onStartDrag, //开始拖动事件
                onDrag: this.opts.onDrag, //拖动中事件
                onStopDrag: this.opts.onStopDrag //拖动结束事件
            };
            if (dragOpt.isProxy && this.opts.header) {
                dragOpt["onMouseDown"] = function (state, e) {
                    if (e.target.nodeName === "I") {
                        return false;
                    }
                };
            }
            if (this.opts.draggableHandler === 'header' && this.opts.header) {
                dragOpt["handler"] = this.$header;
            }
            jqObj.draggable(dragOpt);
        }
        if (toolbar) {
            var _h = toolbar.outerHeight();
            _this.$body.css({
                "border-bottom-width": _h + "px",
                "border-bottom-style": "solid",
                "border-bottom-color": "#ffffff"
            });
        }
        if (typeof this.opts.onCreated === 'function') {
            this.opts.onCreated.call(this.jqObj, this.$body, this.$header);
        }
        _this.$body.css("overflow", "auto");
        if ($B.isUrl(this.opts.content) || this.opts.url !== "") {
            var _url =  this.opts.url;
            if($B.isUrl(this.opts.content)){
                _url = this.opts.content;
            }
            this.load({
                url: _url,
                dataType: this.opts.dataType
            });
        }
    }
    Panel.prototype = {
        constructor: Panel,
        /**用于加载数据
         *args={
            url: null,//url地址
            dataType:'html/json/iframe'
        }**/
        load: function (args) {
            var url = this.opts.url;
            if($B.isUrl(this.opts.content)){
                url = this.opts.content;
            }
            var dataType = this.opts.dataType;
            var _this = this;
            if (args) {
                url = args.url;
                dataType = args.dataType;
            }
            var isFun = typeof this.opts.onLoaded === 'function';           
            if(url.indexOf("?") > 0){
                url = url + "&_t_="+$B.generateMixed(5);
            }else{
                url = url + "?_t_="+$B.generateMixed(5);
            }
            this.url = url;
            var loading = $(loadingHtml);
            loading.appendTo(_this.$body);
            setTimeout(function () {               
                if (dataType === "html") {                   
                    $B.htmlLoad({
                        target: _this.$body,
                        url: url,
                        onLoaded: function () {
                            loading.fadeOut(function(){
                                $(this).remove();
                            });
                            if (isFun) {
                                _this.opts.onLoaded.call(_this.$body,{});
                            }
                            $B.bindTextClear(_this.$body);
                        }
                    });
                } else if (dataType === "json") {                   
                    $B.request({
                        dataType: 'json',
                        url: url,
                        ok: function (message, data) {
                            if (isFun) {
                                _this.opts.onLoaded.call(_this.$body, data);
                            }
                        },
                        final: function (res) {
                            loading.fadeOut(function(){
                                $(this).remove();
                            });
                        }
                    });
                } else {
                    if (!_this.iframe) {                        
                        _this.iframe = $(iframeHtml);
                        _this.iframe.on("load", function (e) {
                            var _t = $(this);
                            var url = _t.attr("src");
                            if (url !== "") {                         
                                if (isFun) {
                                    _this.opts.onLoaded.call(_this.$body,{});
                                }
                                try {
                                    loading.fadeOut(function(){
                                        $(this).remove();
                                    });
                                } catch (ex) {
                                    
                                }
                                var ua = window.navigator.userAgent;
                                var isFirefox = ua.indexOf("Firefox") !== -1;
                                if (isFirefox) {
                                    try {
                                        $(this.contentDocument.body).find("a").each(function () {
                                            var $a = $(this);
                                            if ($a.attr("href").toLowerCase().indexOf("javascript") > -1) {
                                                $a.attr("href", "#");
                                            }
                                        });
                                    } catch (ex) {}
                                }
                            }
                        });
                    }    
                    _this.iframe[0].src = url;   
                    _this.iframe.appendTo(_this.$body) ;
                }
            }, 10);
        },
        /**
         * 更新静态内容 content
         * ***/
        updateContent: function (content) {
            this.$body.html(content);
        },
        /**
         * args={title:'标题',iconCls:'图标样式'}/args=title
         ***/
        setTitle: function (args) {
            if (!this.opts.header) {
                return;
            }
            if (typeof args === 'string') {
                this.$header.children().children("h1").html(args);
            } else {
                if (args.title) {
                    this.$header.children().children("h1").html(args.title);
                }
                if (args.iconCls) {
                    var icon = this.$header.children().children(".k_panel_header_icon").find("i.fa");
                    icon.attr("class","fa "+args.iconCls);
                }
            }
        },
        /**关闭
         * ifForce:是否强制关闭，强制则忽略onClose的返回
         * **/
        close: function (isForce) {
            if(this.opts.closeType === "destroy"){
                this.destroy();
                return;
            }
            var _this = this;
            var goClose = true;
            if (typeof _this.opts.onClose === 'function') {
                goClose = _this.opts.onClose();
            }
            if (isForce || goClose) {
                var fn = function () {
                    // var _scrollId = _this.$body.id;                    
                    // var $b = $("body");
                    // $b.children("#" + _scrollId).remove();
                    // $b.children("#" + _scrollId + '-hr').remove();
                    _this._invokeClosedFn();
                };
                if(_this.opts.position){
                    if(_this.opts.position === "bottom"){
                        this.jqObj.fadeOut(200, fn);
                    }else{
                        this.jqObj.animate({top:-2000},500,fn);
                    }
                }else{
                    this.jqObj.fadeOut(200, fn);
                }
            }
        },
        /**显示**/
        show: function () {
            if (this.jqObj) {
                this.jqObj.fadeIn(200, function () {});
            }
        },
        _invokeClosedFn:function(){
            this.jqObj.hide();
            var _this = this;
            if (typeof _this.opts.onClosed === 'function') {
                try {
                    _this.opts.onClosed.call(this.jqObj);
                } catch (e) {
                    _this.error(e);
                }
            }
        },
        /**
         * 销毁
         * **/
        destroy: function () {
            var _this = this;
            for (var i = 0, len = this.toolArray.length; i < len; ++i) {
                this.toolArray[i].destroy();
            }
            if (typeof _this.opts.onClose === 'function') {
                _this.opts.onClose();
            }
            if (this.jqObj.css("display") === "block") {
                var f = function () {                   
                    _this._invokeClosedFn();
                    _this.jqObj.remove();
                    _this.super.destroy.call(_this);
                };
                this.jqObj.fadeOut("fast", f);
            } else {
                _this._invokeClosedFn();
                this.jqObj.remove();
                this.super.destroy.call(this);
            }
        },
        /*重设大小
         * args={width:,height:}
         * **/
        resize: function (args, callBack) {
            var rs = {},
                _this = this;
            if (args.width) {
                rs["width"] = args.width;
            }
            if (args.height) {
                rs["height"] = args.height;
            }
            this.jqObj.css(rs);
            if (typeof _this.opts.onResized === 'function') {
                setTimeout(function(){
                    _this.opts.onResized();
                },10);                
            }
        },
        /***获取大小***/
        getSize: function () {
            return {
                width: this.jqObj.outerWidth(),
                height: this.jqObj.outerHeight()
            };
        },
        /**获取iframe**/
        getIfr: function () {
            if (this.opts.dataType !== 'iframe') {
                return;
            }
            return this.$body.children("iframe")[0];
        },
        hide: function () {
            this.close(true);
        },
        setAttr: function (attr) {
            this.jqObj.attr(attr);
        }
    };
    $B["Panel"] = Panel;
    return Panel;
}));